package com.youyicloud.api;


import com.alibaba.fastjson.JSONObject;
import com.youyicloud.constants.Constants;
import com.youyicloud.feign.CommonFeignClient;
import com.youyicloud.utils.VerifySignUtil;
import com.youyicloud.vo.ResponseBodyEntity;
import com.youyicloud.wechat.sdk.SignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("wechat")
@Slf4j
public class WechatApi {

	@Value("${wechat.appId}")
	private String appId;
	@Value("${wechat.secret}")
	private String secret;

	@Autowired
	private RestTemplate restTemplate;
	@Autowired
	private CommonFeignClient commonFeignClient;
	/**
	 * scope:snsapi_userinfo
	 * @return
	 */
	@RequestMapping("/authorize")
	public String authorize(String redirectUri,String scope,String state){
		String redirectUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appId+"&redirect_uri="+redirectUri+"&response_type=code&scope="+scope+"&state="+state+"#wechat_redirect";
		log.info("微信网页授权....,地址:{}",redirectUrl);
		return "redirect:"+redirectUrl;
	}

	@RequestMapping("/getOpenId")
	public String getOpenId(RedirectAttributes attr, @RequestParam("code") String code,
							@RequestParam("state") String state) throws Exception{
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={secret}&code={code}&grant_type={grantType}";
		Map<String,Object> urlVariables = new HashMap<String,Object>();
		urlVariables.put("appId", appId);
		urlVariables.put("secret", secret);
		urlVariables.put("grantType", "authorization_code");
		urlVariables.put("code", code);
		ResponseEntity<String> responseEntity =restTemplate.getForEntity(url, String.class, urlVariables);
		String jsonStr = responseEntity.getBody();
		JSONObject jsonObject =JSONObject.parseObject(jsonStr);
		log.info("微信登陆信息:{}",jsonObject.toJSONString());

		String accessToken = jsonObject.getString("access_token");
		String openid = jsonObject.getString("openid");
		String userInfoJson = getUserInfo(openid,accessToken);
		log.info("获取的用户信息:{}",userInfoJson);
		return "redirect:"+state+"?openId="+openid;
	}

	@GetMapping("/getUserInfo")
	public String getUserInfo(String openId,String accessToken) throws Exception{
		String url = "https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openId}&lang=zh_CN";
		Map<String,Object> urlVariables = new HashMap<String,Object>();
		urlVariables.put("openId", openId);
		urlVariables.put("access_token", accessToken);
		ResponseEntity<String> responseEntity =restTemplate.getForEntity(url, String.class, urlVariables);
		String jsonStr = responseEntity.getBody();
		JSONObject jsonObject =JSONObject.parseObject(jsonStr);
		log.info("微信登陆信息:{}",jsonObject.toJSONString());
		String nickName = jsonObject.getString("nickname");
		return nickName;
	}

	@RequestMapping("/sign")
	public @ResponseBody ResponseBodyEntity share(String openId,String linkUrl) throws UnsupportedEncodingException {
		log.info("openId:{}",openId);
		String jsapiTicket = commonFeignClient.getJsapiTicket(appId,secret);
		log.info("jsapiTicket信息:{}",jsapiTicket);
		ResponseBodyEntity responseBodyEntity = new ResponseBodyEntity();
		Map<String, String> resultMap = SignUtil.sign(jsapiTicket, linkUrl);
		resultMap.put("type", "link");
		resultMap.put("dataUrl", "");
		resultMap.put("appId", appId);
		log.info("签名信息:{}",resultMap);
		responseBodyEntity.setState(Constants.SUCCEED);
		responseBodyEntity.setData(resultMap);
		return responseBodyEntity;
	}

	/**
	 * 微信服务器认证地址
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@GetMapping("/checkWebcatId")
	public void checkWebcatId(HttpServletRequest request, HttpServletResponse response) throws Exception{
		log.info("微信调用事件...");
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		PrintWriter print;
		if (isGet) {
			// 微信加密签名
			String signature = request.getParameter("signature");
			// 时间戳
			String timestamp = request.getParameter("timestamp");
			// 随机数
			String nonce = request.getParameter("nonce");
			// 随机字符串
			String echostr = request.getParameter("echostr");
			log.info("微信服务器认证地址.....加密签名:{},时间戳:{},随机数:{},随机字符串:{}",signature,timestamp,nonce,echostr);
			// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
			if (signature != null && VerifySignUtil.checkSignature(signature, timestamp, nonce)) {
				try {
					print = response.getWriter();
					print.write(echostr);
					print.flush();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
